﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Web;

namespace CollegeShop.Api.Framework
{
    public static class ImageHelper
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="fs">图片二进制流</param>
        /// <param name="path">路径，包括图片的名称</param>
        /// <returns>true:成功 false:失败</returns>
        public static bool UploadImage(byte[] fs, string path)
        {
            try
            {
                MemoryStream ms = new MemoryStream(fs);

                path = HttpContext.Current.Server.MapPath(path);
                //创建目录  
                string dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                //原始图片（获取原始图片创建对象，并使用流中嵌入的颜色管理信息）  
                System.Drawing.Image initImage = System.Drawing.Image.FromStream(ms, true);

                //缩略图宽、高计算  
                double newWidth = 200;
                double newHeight = 200;

                //生成新图  
                //新建一个bmp图片  
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一个画板  
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
                //设置质量  
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色  
                newG.Clear(Color.White);
                //画图  
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //保存缩略图                  
                newImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

                //释放资源  
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }        
    }
}
